<template>
	<view class="content">
		<u-navbar bgColor="#F5F9FC" :placeholder="true" :border="true" height="48px">
			<view slot="left" class="navbar-left">
				<navigator class="back-button">
					<view class="nav-back-content">
						<view class="nav-title">分析</view>
					</view>
				</navigator>
			</view>
		</u-navbar>
		<view class="head">
			<view class="blue-line"></view>
			<view>资产管理</view>
		</view>
		<view class="card">
			<view class="card-moudle" v-for="(item,index) in zcList" :key="index" @click="toBanks(item.url)">
				<image :src="item.img"></image>
				<view>{{item.title}}</view>
			</view>
		</view>
		<view class="head">
			<view class="blue-line"></view>
			<view>财务报表</view>
		</view>
		<view class="card">
			<view class="card-moudle" v-for="(item,index) in financeList" :key="index">
				<image :src="item.img"></image>
				<view>{{item.title}}</view>
			</view>
		</view>

		<view class="head">
			<view class="blue-line"></view>
			<view>账本</view>
		</view>
		<view class="card">
			<view class="card-moudle" v-for="(item,index) in ledgerList" :key="index">
				<image :src="item.img"></image>
				<view>{{item.title}}</view>
			</view>
		</view>

		<!-- 业务分析：还原样式，固定显示0.00 -->
		<view class="head">
			<view class="blue-line"></view>
			<view>业务分析</view>
		</view>
		<view class="bussiness">
			<view class="bussiness-box">
				<view class="bussiness-block">
					<view style="view-align: center;">
						<view class="bussiness-value">0.00(预估)</view>
						<view class="bussiness-title">增值税预估</view>
					</view>
				</view>
				<view class="line-y"></view>
				<view class="bussiness-block">
					<view style="view-align: center;">
						<view class="bussiness-value">0.00(预估)</view>
						<view class="bussiness-title">企业所得税</view>
					</view>
				</view>
			</view>
			<view class="line-box">
				<view class="line"></view>
			</view>
			<view class="bussiness-box">
				<view class="bussiness-box">
					<view class="bussiness-block">
						<view style="view-align: center;">
							<view class="bussiness-value">0.00</view>
							<view class="bussiness-title">未分配利润</view>
						</view>
					</view>
					<view class="line-y"></view>
					<view class="bussiness-block">
						<view style="view-align: center;">
							<view class="bussiness-value">0.00</view>
							<view class="bussiness-title">股息分红</view>
						</view>
					</view>
				</view>
			</view>
		</view>

		<view class="head">
			<view class="blue-line"></view>
			<view>盈亏</view>
			<view style="display: flex;align-items: flex-end;">
				<view class="time">(统计至{{time}})</view>
			</view>
		</view>
		<view class="profit">
			<view class="profit-block">
				<view class="item">
					<view class="profit-value">{{(profitData.profit || 0).toFixed(2)}}</view>
					<view class="profit-title">盈利</view>
				</view>
			</view>
			<view class="line-y"></view>
			<view class="profit-block">
				<view class="item">
					<view class="profit-value" style="color: rgba(8, 194, 146, 1) !important">
						{{(profitData.income || 0).toFixed(2)}}
					</view>
					<view class="profit-title">收入</view>
				</view>
			</view>
			<view class="line-y"></view>
			<view class="profit-block">
				<view class="item">
					<view class="profit-value" style="color: rgba(241, 97, 35, 1) !important">
						{{(profitData.expenditure || 0).toFixed(2)}}
					</view>
					<view class="profit-title">支出</view>
				</view>
			</view>
		</view>

		<view class="head">
			<view class="blue-line"></view>
			<view>开票收支</view>
			<view style="display: flex;align-items: flex-end;">
				<view class="time">(统计至{{time}})</view>
			</view>
		</view>
		<view class="profit">
			<view class="profit-block" style="width: calc(100% / 2 - 32rpx) !important;">
				<view class="item">
					<view class="profit-value" style="color: rgba(8, 194, 146, 1) !important">
						{{(invoiceData.issueTotal || 0).toFixed(2)}}
					</view>
					<view class="profit-title">开票收入</view>
				</view>
			</view>
			<view class="line-y"></view>
			<view class="profit-block" style="width: calc(100% / 2 - 32rpx) !important;">
				<view class="item">
					<view class="profit-value" style="color: rgba(241, 97, 35, 1) !important">
						{{(invoiceData.receiveTotal || 0).toFixed(2)}}
					</view>
					<view class="profit-title">开票支出</view>
				</view>
			</view>
		</view>

		<view class="head">
			<view class="blue-line"></view>
			<view>未开票收支</view>
			<view style="display: flex;align-items: flex-end;">
				<view class="time">(统计至{{time}})</view>
			</view>
		</view>
		<view class="profit">
			<view class="profit-block" style="width: calc(100% / 2 - 32rpx) !important;">
				<view class="item">
					<view class="profit-value" style="color: rgba(8, 194, 146, 1) !important">
						{{(accountData.unissuedIncome || 0).toFixed(2)}}
					</view>
					<view class="profit-title">未开票收入</view>
				</view>
			</view>
			<view class="line-y"></view>
			<view class="profit-block" style="width: calc(100% / 2 - 32rpx) !important;">
				<view class="item">
					<view class="profit-value" style="color: rgba(241, 97, 35, 1) !important">
						{{(accountData.unissuedExpenditure || 0).toFixed(2)}}
					</view>
					<view class="profit-title">未开票支出</view>
				</view>
			</view>
		</view>

		<!-- 银行收支：对接银行流水数据源 -->
		<view class="head">
			<view class="blue-line"></view>
			<view>银行收支</view>
			<view style="display: flex;align-items: flex-end;">
				<view class="time">(统计至{{time}})</view>
			</view>
		</view>
		<view class="profit" @click="toBanks('/pages/bank/statement')">
			<view class="profit-block">
				<view class="item">
					<view class="profit-value" style="color: rgba(8, 194, 146, 1) !important">
						{{(bankFlowData.totalIncome || 0).toFixed(2)}}
					</view>
					<view class="profit-title">银行收入</view>
				</view>
			</view>
			<view class="line-y"></view>
			<view class="profit-block">
				<view class="item">
					<view class="profit-value" style="color: rgba(241, 97, 35, 1) !important">
						{{(bankFlowData.totalExpense || 0).toFixed(2)}}
					</view>
					<view class="profit-title">银行支出</view>
				</view>
			</view>
			<view class="line-y"></view>
			<view class="profit-block">
				<view class="item">
					<view class="profit-value">{{(bankFlowData.currentBalance || 0).toFixed(2)}}</view>
					<view class="profit-title">银行余额</view>
				</view>
			</view>
		</view>

		<view style="height: 40rpx;"></view>
	</view>
</template>
<script>
	import {
		currentCompanyApi
	} from "@/api/auth.js"

	export default {
		data() {
			return {
				zcList: [{
					title: '资产管理',
					img: '../../static/images/table.png',
					url: '/pages/Assetmanage/Assetmanage'
				}],
				financeList: [{
					title: '利润表',
					img: '../../static/images/up-yellow.png',
					url: ''
				}, {
					title: '资产负债表',
					img: '../../static/images/up-red.png',
					url: ''
				}, {
					title: '现金流量表',
					img: '../../static/images/up-blue.png',
					url: ''
				}],
				ledgerList: [{
					title: '总账',
					img: '../../static/images/piechart.png',
					url: ''
				}, {
					title: '明细账',
					img: '../../static/images/table.png',
					url: ''
				}, {
					title: '余额表',
					img: '../../static/images/invoice-cicle.png',
					url: ''
				}],
				time: '',
				// 公司相关信息
				http: uni.$u.http,
				isLogin: false,
				companyId: null,
				companyInfo: {},
				// 初始化所有数据为0，彻底杜绝undefined
				profitData: {
					profit: 0,
					income: 0,
					expenditure: 0
				},
				invoiceData: {
					issueTotal: 0,
					receiveTotal: 0
				},
				accountData: {
					unissuedIncome: 0,
					unissuedExpenditure: 0
				},
				// 银行流水数据（对接银行流水页面）
				bankFlowData: {
					totalIncome: 0, // 银行总收入
					totalExpense: 0, // 银行总支出
					currentBalance: 0, // 银行当前余额
					initialBalance: 0 // 银行初期余额
				}
			}
		},
		onShow() {
			// 检查登录状态
			this.isLogin = uni.getStorageSync('isLogin')
			if (!this.isLogin) {
				uni.reLaunch({
					url: '/pages/login/login'
				})
				return
			}
			// 获取当前公司信息
			this.getCurrentCompany()
		},
		methods: {
			toBanks(e) {
				uni.navigateTo({
					url: e
				})
			},
			// 获取当前公司信息
			getCurrentCompany() {
				currentCompanyApi().then(res => {
					if (res.code == 200 && res.data) {
						this.companyInfo = res.data
						this.companyId = res.data.id
						uni.setStorageSync('companyInfo', res.data)
						// 初始化时间
						this.time = this.$u.timeFormat(Date.now(), 'yyyy-mm-dd hh:MM')
						// 获取银行流水数据
						this.getBankFlowSummary()
						// 获取盈亏数据（对接记账接口）
						this.getProfitData()
					} else {
						// 未绑定公司，跳转到绑定页面
						uni.navigateTo({
							url: '/subpackageTwo/pages/addCompany/addCompany'
						})
					}
				})
			},

			/**
			 * 核心修复：获取当前月记账数据计算盈亏（对接真实记账接口）
			 */
			async getProfitData() {
				if (!this.companyId) return

				try {
					// 1. 计算当前月的起止日期（当月1号 到 当月最后一天）
					const now = new Date()
					const year = now.getFullYear()
					const month = now.getMonth()
					// 当月第一天
					const startDate = new Date(year, month, 1)
					// 当月最后一天
					const endDate = new Date(year, month + 1, 0)

					// 2. 格式化日期为 yyyy-mm-dd 格式（匹配接口要求）
					const formatDate = (date) => {
						const y = date.getFullYear()
						const m = String(date.getMonth() + 1).padStart(2, '0')
						const d = String(date.getDate()).padStart(2, '0')
						return `${y}-${m}-${d}`
					}

					// 3. 调用记账记录接口（和记账页面用同一个接口）
					const res = await this.http.get('/VipAccountingRecord/list', {
						params: {
							companyId: this.companyId,
							pageSize: 1000, // 一次性获取当月所有数据
							startDate: formatDate(startDate),
							endDate: formatDate(endDate)
						}
					})

					// 4. 处理接口返回数据
					if (res.code === 200 && res.data && res.data.data) {
						const recordList = res.data.data || []

						// 5. 计算当月总收入、总支出（和记账页面逻辑一致）
						// 收入：recordType=0，支出：recordType=1
						this.profitData.income = recordList
							.filter(record => record.recordType === 0) // 收入类型
							.reduce((sum, record) => sum + Number(record.amount || 0), 0)

						this.profitData.expenditure = recordList
							.filter(record => record.recordType === 1) // 支出类型
							.reduce((sum, record) => sum + Math.abs(Number(record.amount || 0)), 0) // 取绝对值确保支出为正

						// 6. 计算利润（收入 - 支出）
						this.profitData.profit = this.profitData.income - this.profitData.expenditure

						console.log('当前月记账盈亏数据：', {
							总收入: this.profitData.income,
							总支出: this.profitData.expenditure,
							利润: this.profitData.profit
						})
					}
				} catch (err) {
					console.error('获取盈亏数据失败', err)
					// 异常时重置为0，避免页面显示NaN
					this.profitData = {
						profit: 0,
						income: 0,
						expenditure: 0
					}
				}
			},

			// 获取银行流水汇总数据（保持不变）
			async getBankFlowSummary() {
				if (!this.companyId) return
				try {
					// 1. 获取当前年月
					const now = new Date()
					const year = now.getFullYear()
					const month = (now.getMonth() + 1).toString().padStart(2, '0')
					const selectedDate = `${year}-${month}`

					// 2. 获取银行流水列表（汇总收支）
					const flowRes = await this.http.get('/VipBankFlow/list', {
						params: {
							companyId: this.companyId,
							pageNumber: 1,
							pageSize: 1000, // 一次性获取当月所有数据
							tradeDate: selectedDate
						}
					})

					// 3. 获取初期余额
					const balanceRes = await this.http.get('/VipBalanceConfig/list', {
						params: {
							companyId: this.companyId,
							pageSize: 1
						}
					})

					// 4. 计算银行流水汇总数据
					if (flowRes.code === 200 && flowRes.data) {
						const transactions = flowRes.data.data || []
						// 计算总收入/总支出
						this.bankFlowData.totalIncome = transactions
							.filter(item => Number(item.incomeType) === 1)
							.reduce((sum, item) => sum + (Number(item.amount) || 0), 0)
						this.bankFlowData.totalExpense = transactions
							.filter(item => Number(item.incomeType) === 0)
							.reduce((sum, item) => sum + (Number(item.amount) || 0), 0)
					}

					// 5. 设置初期余额和当前余额
					if (balanceRes.code === 200 && balanceRes.data && balanceRes.data.data.length > 0) {
						this.bankFlowData.initialBalance = Number(balanceRes.data.data[0].initialBalance) || 0
					}
					// 计算当前余额 = 初期余额 + 收入 - 支出
					this.bankFlowData.currentBalance =
						this.bankFlowData.initialBalance + this.bankFlowData.totalIncome - this.bankFlowData
						.totalExpense

				} catch (err) {
					console.error('获取银行流水汇总失败', err)
					// 异常时仍保证显示0，不出现undefined
					this.bankFlowData = {
						totalIncome: 0,
						totalExpense: 0,
						currentBalance: 0,
						initialBalance: 0
					}
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.content {
		padding: 28rpx;

		.navbar-left {
			.nav-back-content {
				display: flex;
				align-items: center;

				.nav-title {
					font-size: 34rpx;
					font-weight: bold;
					color: #1e88e5;
					margin-left: 16rpx;
				}
			}
		}

		.head {
			height: 40rpx;
			line-height: 40rpx;
			display: flex;
			align-items: center;
			margin: 24rpx 0rpx 20rpx 0rpx;

			.view {
				font-size: 30rpx;
				margin-left: 12rpx;
			}

			.blue-line {
				width: 12rpx;
				height: 44rpx;
				border-radius: 5rpx;
				margin-right: 5rpx;
				background: rgb(65, 136, 239);
			}

			.time {
				font-size: 20rpx;
				color: rgb(128, 128, 128);
				margin-left: 10rpx;
			}
		}

		.card {
			width: calc(100% - 120rpx);
			height: 136rpx;
			border-radius: 10rpx;
			background: rgba(255, 255, 255, 1);
			box-shadow: 0rpx 2rpx 4rpx rgba(0, 0, 0, 0.1);
			display: flex;
			justify-content: space-between;
			align-items: center;
			font-size: 26rpx;
			padding: 24rpx 60rpx;

			.card-moudle {
				view-align: center;

				image {
					width: 100rpx;
					height: 100rpx;
				}
			}
		}

		.bussiness {
			width: 100%;
			height: 298rpx;
			border-radius: 10rpx;
			background: rgba(255, 255, 255, 1);
			box-shadow: 0rpx 2rpx 4rpx rgba(0, 0, 0, 0.1);

			.bussiness-box {
				width: 100%;
				height: 148rpx;
				display: flex;
				justify-content: space-between;
				align-items: center;

				.line-y {
					width: 2rpx;
					height: 40rpx;
					background: rgba(229, 229, 229, 1);
				}

				.bussiness-block {
					width: calc(50% - 32rpx);
					height: 148rpx;
					display: flex;
					align-items: center;
					justify-content: center;
					padding: 0rpx 30rpx;

					.bussiness-value {
						height: 54rpx;
						font-size: 30rpx;
						font-weight: 700;
						color: rgb(51, 51, 51);
						overflow: hidden;
						white-space: nowrap;
						view-overflow: ellipsis;
					}

					.bussiness-title {
						font-size: 22rpx;
						color: rgb(128, 128, 128);
					}
				}
			}

			.line-box {
				width: 100%;
				height: 2rpx;
				display: flex;
				justify-content: center;

				.line {
					width: 90rpx;
					height: 2rpx;
					background: rgba(229, 229, 229, 1);
				}
			}
		}

		.profit {
			width: 100%;
			height: 134rpx;
			border-radius: 10rpx;
			background: rgba(255, 255, 255, 1);
			box-shadow: 0rpx 2rpx 4rpx rgba(0, 0, 0, 0.1);
			display: flex;
			justify-content: space-between;
			align-items: center;

			.line-y {
				width: 2rpx;
				height: 40rpx;
				background: rgba(229, 229, 229, 1);
			}

			.profit-block {
				width: calc(100% / 3 - 32rpx);
				height: 138rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				padding: 0rpx 30rpx;

				.item {
					view-align: center;
					width: 100%;
					overflow: hidden;
					white-space: nowrap;
					view-overflow: ellipsis;

					.profit-value {
						width: 100%;
						height: 54rpx;
						font-size: 28rpx;
						font-weight: 700;
						color: rgb(51, 51, 51);
						overflow: hidden;
						white-space: nowrap;
						view-overflow: ellipsis;
					}

					.profit-title {
						font-size: 22rpx;
						color: rgb(128, 128, 128);
					}
				}
			}
		}
	}
</style>